import { getUserInfo } from "../service/user.service.js";
import bcrypt from "bcryptjs";
import {
  USER_NAME_OR_PASSWORD_IS_REQUIRED,
  USER_NAME_IS_EXISTS,
  USER_NAME_OR_PASSWORD_IS_INVALID,
  USER_NOT_EXISTS,
  LOGIN_ERROR,
} from "../constant/err.type.js";
export async function userValidator(ctx, next) {
  const { userName, passWord } = ctx.request.body;
  // 判断用户名和密码是否存在
  if (!userName || !passWord) {
    // ctx.body = {
    //   code: 10001,
    //   message: "用户名或密码不能为空",
    // };
    ctx.app.emit("error", USER_NAME_OR_PASSWORD_IS_REQUIRED, ctx);
    return;
  }

  await next();
}

export async function verifyUserUniqueness(ctx, next) {
  const { userName } = ctx.request.body;

  // 判断用户是否是唯一
  const user = await getUserInfo({
    userName,
  });
  if (user && user.userName) {
    ctx.app.emit("error", USER_NAME_IS_EXISTS, ctx);

    return;
  }
  await next();
}

//密码加密
export async function cryptPassword(ctx, next) {
  const { passWord } = ctx.request.body;
  const salt = bcrypt.genSaltSync(10);
  const hash = bcrypt.hashSync(passWord, salt);
  ctx.request.body.passWord = hash;
  await next();
}
//判断用户是否存在且密码是否匹配
export async function verifyLogin(ctx, next) {
  const { userName, passWord } = ctx.request.body;
  try {
    const res = await getUserInfo({ userName });

    if (!res) {
      return ctx.app.emit("error", USER_NOT_EXISTS, ctx);
    }
    if (!bcrypt.compareSync(passWord, res.passWord)) {
      return ctx.app.emit("error", USER_NAME_OR_PASSWORD_IS_INVALID, ctx);
    }

    await next();
  } catch (err) {
    ctx.app.emit("error", LOGIN_ERROR, ctx);
  }
}
